/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the MIT License, (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import CryptoJS from 'crypto-js';

export { CryptoJS }

CryptoJS.lib.WordArray.random = function (nBytes) {
    var words: number[] = [];
    var m_w;
    var r = (function (m_w) {
        var m_z = 0x3ade68b1;
        var mask = 0xffffffff;

        return function () {
            m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
            m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
            var result = ((m_z << 0x10) + m_w) & mask;
            result /= 0x100000000;
            result += 0.5;
            return result * (Math.random() > .5 ? 1 : -1);
        }
    });

    for (var i = 0, rcache; i < nBytes; i += 4) {
        var _r = r((rcache || Math.random()) * 0x100000000);

        rcache = _r() * 0x3ade67b7;
        words.push((_r() * 0x100000000) | 0);
    }
    return CryptoJS.lib.WordArray.create(words, nBytes);
};

CryptoJS.enc.Utf8.stringify = function (wordArray) {
    try {
        return decodeURI(CryptoJS.enc.Latin1.stringify(wordArray));
    } catch (e) {
        throw new Error('Malformed UTF-8 data');
    }
}

CryptoJS.enc.Utf8.parse = function (utf8Str) {
    return CryptoJS.enc.Latin1.parse(encodeURI(utf8Str));
}
